<template>
  <el-dialog
    :title="title"
    :visible.sync="isVisible"
    :width="width"
    :before-close="handleClose"
    :lock-scroll="true"
    :close-on-click-modal="false"
    custom-class="pub_dialog"
    @open="getData"
  >
    <VForm
      ref="vformComponents"
      :form="formData.form"
      :options="formData.options"
      :rules="formData.rules"
      :labelWidth="formData.labelWidth"
      :rowspan="rowspan"
      @toLoadMethods="toLoadMethods"
    ></VForm>

    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="sure">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  alarmRecordDetail,
  alarmRecordUpdate,
  alarmRecordAdd
} from '@/api/alarm/record'
import VForm from "@/components/VForm";
import {alarmFacilityList} from "@/api/alarm/facility";
import {alarmMonitorPointList} from "@/api/alarm/point";
import {alarmDeviceList} from "@/api/alarm/device";

export default {
  components: {
    VForm,
  },
  props: {
    width: {
      type: String,
      default: "70%",
    },
    title: {
      type: String,
      default: "详情",
    },
    id: {},
    openType: {
      type: String,
      default: "add"
    },
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    'width': {
      handler(newVal, oldVal) {
        console.log('newVal===', newVal, oldVal)
        let w = this.width.split('%')[0]
        if (w >= 60) {
          this.rowspan = 2
        } else {
          this.rowspan = 1
        }
      },
      deep: true,
      immediate: true
    },
    'modeType': {
      handler(newVal, oldVal) {
        this.formData.form.modeType = newVal;
      },
      deep: true,
      immediate: true
    },
    'alarmType': {
      handler(newVal, oldVal) {
        this.formData.form.alarmType = newVal;
      },
      deep: true,
      immediate: true
    },
    'alarmTypeOptions': {
      handler(newVal, oldVal) {
        this.formData.options.forEach(t => {
          if (t.key == 'alarmType') {
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },
    'facilityIdOptions': {
      handler(newVal, oldVal) {
        this.formData.options.forEach(t => {
          if (t.key == 'facilityId') {
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },
    'monitorObjectIdOptions': {
      handler(newVal, oldVal) {
        this.formData.options.forEach(t => {
          if (t.key == 'pointId') {
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },
    'deviceIdOptions': {
      handler(newVal, oldVal) {
        this.formData.options.forEach(t => {
          if (t.key == 'deviceId') {
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },
    'alarmLevelOptions': {
      handler(newVal, oldVal) {
        this.formData.options.forEach(t => {
          if (t.key == 'maxAlarmLevel' || t.key == 'nowAlarmLevel') {
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },
    'alarmSourceOptions': {
      handler(newVal, oldVal) {
        this.formData.options.forEach(t => {
          if (t.key == 'alarmSource') {
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },
    'notifyStatusOptions': {
      handler(newVal, oldVal) {
        this.formData.options.forEach(t => {
          if (t.key == 'notifyStatus') {
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },
    'openType':{
      handler(newVal, oldVal) {
        this.formData.options = this.formData.options.filter(t=> !t.readonly)
        if(newVal != 'add'){
          let item = {
            title: "标识码",
            key: "identificationCode",
            type: "text",
            disabled: true,
            readonly:true
          }
          this.formData.options.unshift(item)
        }
      }
    }
  },
  computed: {
    isVisible: {
      get() {
        return this.dialogVisible
      },
      set() {
        this.close()
      }
    }
  },
  data() {
    return {
      modeType: '',

      rowspan: 1,
      dict: {},
      formData: {
        form: {
          modeType: this.modeType,
          identificationCode: "",
          facilityId: "",
          facilityName: "",
          pointId: "",
          pointName: "",
          deviceId: "",
          equipmentName: "",
          alarmCode: "",
          alarmName: "",
          alarmPosition: "",
          monitorItem: "",
          firstAlarmNum: "",
          nowAlarmNum: "",
          firstAlarmTime: "",
          nowAlarmTime: "",
          nowAlarmLevel: "",
          maxAlarmNum: "",
          maxAlarmTime: "",
          maxAlarmLevel: "",
          alarmEndTime: "",
          alarmSource: "",
          alarmType: "1",
          alarmAddress: "",
          lon: "",
          lat: "",
          provinceCode: "",
          cityCode: "",
          countyCode: "",
          areaCode: "",
          recovered: "",
          recoverAt: "",
          handled: "",
          handleResult: "",
          handleBy: "",
          handleAt: "",
          notifyStatus: "",
          notifyAt: "",
          createUser: "",
          updateTime: "",
          updateUser: "",
          mapData:null,
        },
        options: [
          // {
          //   title: "标识码",
          //   key: "identificationCode",
          //   type: "text",
          // },
          {
            title: "设施名称",
            key: "facilityId",
            type: "select",
            event: 'changePonit',
            multiple: false,
            disabled: false,
            option: {
              data: this.facilityIdOptions,
              props: {
                key: "id", // 指定key对应data的字段
                label: "name", // 指定label对应data的字段
                value: "id", // 指定value对应data的字段
              },
            },
          },
          {
            title: "点位名称",
            key: "pointId",
            type: "select",
            event: 'changeDevice',
            multiple: false,
            disabled: false,
            option: {
              data: this.monitorObjectIdOptions,
              props: {
                key: "id", // 指定key对应data的字段
                label: "pointName", // 指定label对应data的字段
                value: "id", // 指定value对应data的字段
              },
            },
          },
          {
            title: "设备名称",
            key: "deviceId",
            type: "select",
            event: 'changeItem',
            multiple: false,
            disabled: false,
            option: {
              data: this.deviceIdOptions,
              props: {
                key: "id", // 指定key对应data的字段
                label: "name", // 指定label对应data的字段
                value: "id", // 指定value对应data的字段
              },
            },
          },
          {
            title: "报警代码",
            key: "alarmCode",
            type: "text",
          },
          {
            title: "报警名称",
            key: "alarmName",
            type: "text",
          },
          {
            title: "报警地址",
            type:'mapPosition',
            key:'mapData',
          },
          {
            title: "报警部位",
            key: "alarmPosition",
            type: "text",
          },
          {
            title: "监测项",
            key: "monitorItem",
            type: "text",
            disabled: true,
            placeholder:"选择设备自动获取"
          },
          {
            title: "监测项代码",
            key: "monitorItemCode",
            type: "text",
            disabled: true,
            placeholder:"选择设备自动获取"
          },
          {
            title: "初次报警值",
            key: "firstAlarmNum",
            type: "text",
          },
          {
            title: "初次报警时间",
            key: "firstAlarmTime",
            type: "datetime",
          },
          {
            title: "当前报警值",
            key: "nowAlarmNum",
            type: "text",
          },
          {
            title: "当前报警时间",
            key: "nowAlarmTime",
            type: "datetime",
          },
          {
            title: "当前报警级别",
            key: "nowAlarmLevel",
            type: "select",
            multiple: false,
            option: {
              data: this.alarmLevelOptions,
              props: {
                key: "id", // 指定key对应data的字段
                label: "label", // 指定label对应data的字段
                value: "value", // 指定value对应data的字段
              },
            },
          },
          {
            title: "最高报警值",
            key: "maxAlarmNum",
            type: "text",
          },
          {
            title: "最高报警时间",
            key: "maxAlarmTime",
            type: "datetime",
          },
          {
            title: "最高报警级别",
            key: "maxAlarmLevel",
            type: "select",
            multiple: false,
            option: {
              data: this.alarmLevelOptions,
              props: {
                key: "id", // 指定key对应data的字段
                label: "label", // 指定label对应data的字段
                value: "value", // 指定value对应data的字段
              },
            },
          },
          {
            title: "报警结束时间",
            key: "alarmEndTime",
            type: "datetime",
          },
          {
            title: "报警来源",
            key: "alarmSource",
            type: "select",
            multiple: false,
            option: {
              data: this.alarmSourceOptions,
              props: {
                key: "id", // 指定key对应data的字段
                label: "label", // 指定label对应data的字段
                value: "value", // 指定value对应data的字段
              },
            },
          },
          {
            title: "报警类型",
            key: "alarmType",
            type: "select",
            multiple: false,
            disabled: true,
            option: {
              data: this.alarmTypeOptions,
              props: {
                key: "id", // 指定key对应data的字段
                label: "label", // 指定label对应data的字段
                value: "value", // 指定value对应data的字段
              },
            },
          },
          // {
          //   title: "报警地址",
          //   key: "alarmAddress",
          //   type: "text",
          // },
        ],
        rules: {
          // identificationCode: [
          //   {required: true, message: '请输入', trigger: 'blur'},
          //   {max: 20, message: '长度最大为20个字符', trigger: 'blur'}
          // ],
          facilityId: [{required: true, message: '请输入', trigger: 'blur'},],
          pointId: [{required: true, message: '请输入', trigger: 'blur'},],
          deviceId: [{required: true, message: '请输入', trigger: 'blur'},],
          equipmentName: [
            {max: 100, message: '长度最大为100个字符', trigger: 'blur'}
          ],
          alarmCode: [
            {required: true, message: '请输入', trigger: 'blur'},
            {max: 64, message: '长度最大为64个字符', trigger: 'blur'}
          ],
          alarmName: [
            {required: true, message: '请输入', trigger: 'blur'},
            {max: 128, message: '长度最大为128个字符', trigger: 'blur'}
          ],
          alarmPosition: [
            {required: true, message: '请输入', trigger: 'blur'},
            {max: 64, message: '长度最大为64个字符', trigger: 'blur'}
          ],
          monitorItem: [
            {required: true, message: '请输入', trigger: 'blur'},
            {max: 64, message: '长度最大为64个字符', trigger: 'blur'}
          ],
          firstAlarmNum: [{required: true, message: '请输入', trigger: 'blur'},],
          nowAlarmNum: [{required: true, message: '请输入', trigger: 'blur'},],
          firstAlarmTime: [{required: true, message: '请输入', trigger: 'blur'},],
          nowAlarmTime: [{required: true, message: '请输入', trigger: 'blur'},],
          nowAlarmLevel: [{required: true, message: '请输入', trigger: 'blur'},],
          maxAlarmNum: [{required: true, message: '请输入', trigger: 'blur'},],
          maxAlarmTime: [{required: true, message: '请输入', trigger: 'blur'},],
          maxAlarmLevel: [{required: true, message: '请输入', trigger: 'blur'},],
          alarmEndTime: [{required: true, message: '请输入', trigger: 'blur'},],
          alarmSource: [{required: true, message: '请输入', trigger: 'blur'},],
          // alarmAddress: [
          //   {max: 128, message: '长度最大为128个字符', trigger: 'blur'}
          // ],
          lon: [
            {max: 36, message: '长度最大为36个字符', trigger: 'blur'}
          ],
          lat: [
            {max: 36, message: '长度最大为36个字符', trigger: 'blur'}
          ],
          provinceCode: [
            {max: 12, message: '长度最大为12个字符', trigger: 'blur'}
          ],
          cityCode: [
            {max: 12, message: '长度最大为12个字符', trigger: 'blur'}
          ],
          countyCode: [
            {max: 12, message: '长度最大为12个字符', trigger: 'blur'}
          ],
          areaCode: [
            {max: 12, message: '长度最大为12个字符', trigger: 'blur'}
          ],
          recovered: [],
          recoverAt: [],
          handled: [],
          handleResult: [],
          handleBy: [
            {max: 64, message: '长度最大为64个字符', trigger: 'blur'}
          ],
          handleAt: [],
          notifyStatus: [],
          notifyAt: [],
          createUser: [
            {max: 36, message: '长度最大为36个字符', trigger: 'blur'}
          ],
          updateTime: [],
          updateUser: [
            {max: 36, message: '长度最大为36个字符', trigger: 'blur'}
          ],
        },
        labelWidth: "140px",
      },
      // 字典
      facilityIdOptions: [],
      monitorObjectIdOptions: [],
      deviceIdOptions: [],
      alarmTypeOptions: [],
      alarmSourceOptions: [],
      alarmLevelOptions: [],
      notifyStatusOptions: [],
    };
  },
  methods: {
    toLoadMethods(methods) {
      this[methods]()
    },
    submitFormat() {
    },
    loadFormat() {
      let tempMapData = {}
      tempMapData.address = this.formData.form.alarmAddress
      tempMapData.gpsX = parseFloat(this.formData.form.lon)
      tempMapData.gpsY = parseFloat(this.formData.form.lat)
      tempMapData.towncode = this.formData.form.areaCode
      this.formData.form.mapData = tempMapData
    },
    changeItem() {
      const deviceId = this.formData.form.deviceId
      const item = this.deviceIdOptions.find(t => t.id == deviceId)
      if (item) {
        this.formData.form.equipmentName = item.name
        this.formData.form.monitorItem = item.monitorTypeName;
        this.formData.form.monitorItemCode = item.monitorTypeCode;
        this.changeAddress(item)
      }
    },
    changeAddress(data) {
      console.log('changeAddress', data)
      this.formData.form.lon = data.lon
      this.formData.form.lat = data.lat
      this.formData.form.alarmAddress = data.installationAddress

      this.formData.form.provinceCode = data.provinceCode
      this.formData.form.cityCode = data.cityCode
      this.formData.form.countyCode = data.countyCode
      this.formData.form.areaCode = data.areaCode
      let tempMapData = {}
      tempMapData.address = data.installationAddress
      tempMapData.gpsX = parseFloat(data.lon)
      tempMapData.gpsY = parseFloat(data.lat)
      tempMapData.towncode = data.areaCode
      this.formData.form.mapData = tempMapData
    },
    changeDevice() {
      this.deviceIdOptions = []
      const pointId = this.formData.form.pointId
      const item = this.monitorObjectIdOptions.find(t => t.id == pointId)
      if (item) {
        this.formData.form.pointName = item.pointName
      }

      this.getDeviceList(pointId);
    },
    getDeviceList(monitorObjectId) {
      alarmDeviceList({"monitorObjectId": monitorObjectId}).then(res => {
        if (res.code == 200) {
          this.deviceIdOptions = res.data
        } else {
          this.$message({
            message: this.$t('tips.systemException'),
            type: 'error'
          })
        }
      })
    },
    changePonit() {
      this.monitorObjectIdOptions = []
      const facilityId = this.formData.form.facilityId
      const item = this.facilityIdOptions.find(t => t.id == facilityId)
      if (item) {
        this.formData.form.facilityName = item.name
      }
      console.log(facilityId)
      this.getMonitorObjectIdList(facilityId);
    },
    getMonitorObjectIdList(facilityId) {
      alarmMonitorPointList({"facilityId": facilityId}).then(res => {
        if (res.code == 200) {
          this.monitorObjectIdOptions = res.data
        } else {
          this.$message({
            message: this.$t('tips.systemException'),
            type: 'error'
          })
        }
      })
    },
    getCheckBoxData(value, option, type) {
      if (type == "submit") {
        if (value.length == 0) {
          return null
        }
        let temp = [];
        value.forEach(t => {
          let item = option.find(x => x.label == t)
          if (item != undefined) {
            temp.push(item.value)
          }
        })
        return temp.join(",")
      } else {
        if (!value) {
          return []
        } else {
          let data = value.split(",")
          let temp = []
          data.forEach(t => {
            let item = option.find(x => x.value == t)
            if (item != undefined) {
              temp.push(item.label)
            }
          })
          return temp
        }
      }
    },
    sure() {
      this.formData.form.identificationCode="1"
      console.log('sure===', this.formData.form)
      this.$refs.vformComponents.$refs.form.validate().then(res => {
        this.submitFormat()
        if (this.openType == "add") {
          this.add()
        } else {
          this.update()
        }
      })
    },
    add() {
      this.formData.form.id = null
      this.formData.form.alarmType = '1'
      alarmRecordAdd(this.formData.form).then(res => {
        if (res.code == 200) {
          this.$message({
            message: this.$t('tips.createSuccess'),
            type: 'success'
          })
          this.closeSuccess()
        } else {
          this.$message({
            message: this.$t('tips.systemException'),
            type: 'error'
          })
        }
      })
    },
    update() {
      alarmRecordUpdate(this.formData.form).then(res => {
        if (res.code == 200) {
          this.$message({
            message: this.$t('tips.updateSuccess'),
            type: 'success'
          })
          this.closeSuccess()
        } else {
          this.$message({
            message: this.$t('tips.systemException'),
            type: 'error'
          })
        }
      })
    },
    cancel() {
      this.close()
    },
    handleClose(done) {
      done()
      this.close()
    },
    closeSuccess() {
      this.$refs.vformComponents.$refs.form.resetFields();
      this.$emit('success')
    },
    close() {
      this.$refs.vformComponents.$refs.form.resetFields();
      this.$emit('close')
    },
    getData() {
      if (this.openType != "add") {
        alarmRecordDetail(this.id).then(res => {
          if (res.code == 200) {
            this.selectTypeInit(res);
            res.data.nowAlarmLevel = parseInt(res.data.nowAlarmLevel)
            res.data.alarmType = parseInt(res.data.alarmType)
            this.formData.form = res.data
            this.changeDisabled(true);
            this.loadFormat()
          } else {
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        })
      }

      this.changeDisabled(false);
    },
    selectTypeInit(res) {
      //设施
      this.facilityIdOptions = []
      this.getAlarmFacilityList();
      //点位
      this.monitorObjectIdOptions = []
      this.getMonitorObjectIdList(res.data.facilityId);
      //设备
      this.deviceIdOptions = []
      this.getDeviceList(res.data.pointId);
    },
    changeDisabled(value) {
      this.formData.options.find(t => t.key == 'facilityId').disabled = value;
      this.formData.options.find(t => t.key == 'pointId').disabled = value;
      this.formData.options.find(t => t.key == 'deviceId').disabled = value;
    },
    getAlarmFacilityList() {
      alarmFacilityList({"modeType": this.modeType}).then(res => {
        if (res.code == 200) {
          this.facilityIdOptions = res.data
        } else {
          this.$message({
            message: this.$t('tips.systemException'),
            type: 'error'
          })
        }
      });
    },
    initAlarmConfig() {
      let type = this.$route.path
      console.log("path:" + type)
      const config = this.$commonJs.getAlarmPathConfig(this.$route.path)
      this.modeType = config.modeType
    }
  },
  created() {
    this.initAlarmConfig()
    this.alarmSourceOptions = [];
    this.$commonJs.filterDataDict("alarmSource", this.alarmSourceOptions)

    //报警类型
    let recordType = this.$commonJs.getAlarmPathConfig(this.$route.path).recordType
    //alarmRecordType
    this.alarmTypeOptions = [];
    this.$commonJs.filterDataDict(recordType, this.alarmTypeOptions)
    this.formData.form.alarmType = 1

    this.alarmLevelOptions = [];
    this.$commonJs.filterDataDict("alarmLevel", this.alarmLevelOptions)

    //设施
    this.facilityIdOptions = []
    this.getAlarmFacilityList();
  }
};
</script>

<style lang="scss" scoped>

</style>
